﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Galaktika.BI.Silverlight.Controls
{
    using Galaktika.BI.Runtime;
    using Galaktika.BI.Runtime.Services;
    using Galaktika.BI.Extensibility.Dom;
    using Galaktika.BI.Silverlight.Intermediate;
    using Localization = Galaktika.BI.Silverlight.Localization;
    using System.Windows.Controls.Primitives;
    using Galaktika.BI.Silverlight.Services;

    public partial class SimpleButton : ToggleButton, IBindableObject, IEditableObject
    {
        public SimpleButton()
        {
            //base.MinHeight = Common.MinWidth;
            IsToggleButton = false;
            this.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
            this.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
            StackPanel panel = new StackPanel() {Orientation = Orientation.Horizontal};
            this.Content = panel;
            base.DefaultStyleKey = typeof(SimpleButton);
        }

        public string AText { get; set; }

        public Color AForeColor { get; set; }

        public Color ABackColor { get; set; }

        public Color ABackColor2 { get; set; }

        public Font AFont { get; set; }

        public BorderStyles AButtonStyle { get; set; }

        public bool AShowToolTips { get; set; }

        public string AToolTipText { get; set; }

        public Cursor ACursor
        {
            get
            {
                return base.Cursor;
            }
            set
            {
                base.Cursor = value;
            }
        }

        public byte[] AImage { get; set; }

        public BitmapImage ABitmapImage { get; set; }

        public ImageLocation AImageAlignment { get; set; }

        public BrickActionInvoker AActionInvoker { get; set; }

        public virtual bool IsToggleButton { get; set; }

        protected override void OnToggle()
        {
            if (IsToggleButton)
                base.OnToggle();
        }

        protected override void OnClick()
        {
            base.OnClick();

            if (this.AActionInvoker != null && this.AActionInvoker.Action != null)
            {
                var taskMgr = (IUserTaskManager)this.Context.Services.GetService(typeof(IUserTaskManager));
                if (taskMgr != null)
                {
                    taskMgr.RunTask(string.Format(
                                    Localization.AppTask_ExecutingScript,
                                    this.AActionInvoker.Action.Name),
                                state => ScriptEngine.Execute(this, this.AActionInvoker));                    
                }
                
                //IScriptEngine se = (IScriptEngine)this.Context.Services.GetService(typeof(IScriptEngine));
                //if (se != null)
                //{
                //    se.
                //}
            }
        }

        #region IBindableObject Members

        public IBindingContext Context { get; set; }

        private IDictionary<string, IBindingManager> m_Bindings;
        public IDictionary<string, IBindingManager> Bindings
        {
            get
            {
                if (m_Bindings == null)
                {
                    m_Bindings = new SafeDictionary<string, IBindingManager>();
                }

                return m_Bindings;
            }
        }

        #endregion

        #region IEditableObject Members

        public virtual void BeginEdit()
        {
        }

        public virtual void CancelEdit()
        {
        }

        public virtual void EndEdit()
        {
            (this.Content as StackPanel).Children.Clear();
            IUserTaskManager taskMgr = (IUserTaskManager)this.Context.Services.GetService(typeof(IUserTaskManager));
            IExecutionContext exe = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
            if (exe != null && taskMgr != null)
            {
                if (ScriptEngine.ContainsExpression(this.AText) ||
                    (this.AShowToolTips && ScriptEngine.ContainsExpression(this.AToolTipText)))
                {
                    taskMgr.RunTaskAsync(
                    string.Format(Localization.AppTask_ProcessingProperties, base.Name),
                    state =>
                    {
                        string text = exe.Parse(this.Context, this.AText);
                        string tooltip = exe.Parse(this.Context, this.AToolTipText);
                        taskMgr.Dispatcher.BeginInvoke(() =>
                        {
                            if (this.AImage != null && this.AImage.Length > 0)
                            {
                                Image im = new Image() { Stretch = Stretch.None, Margin = new Thickness(0.0, 0.0, 4.0, 0.0) };
                                //VisualStateManager.GoToState(this,"Pressed",false);
                                BitmapImage bmp = new BitmapImage();
                                MemoryStream ms = new MemoryStream();
                                ms.Write(this.AImage, 0, this.AImage.Length);
                                bmp.SetSource(ms);
                                im.Source = bmp;
                                (this.Content as StackPanel).Children.Add(im);
                            }
                            else
                            {
                                if (this.ABitmapImage != null)
                                {
                                    ((StackPanel)this.Content).Children.Add(new Image() { Source = this.ABitmapImage, Margin = new Thickness(0.0, 0.0, 4.0, 0.0) });
                                }
                            }
                            TextBlock tb = new TextBlock();
                            tb.Text = text;
                            (base.Content as StackPanel).Children.Add(tb);
                            if (this.AShowToolTips && !string.IsNullOrEmpty(tooltip))
                            {
                                ToolTipService.SetToolTip(this, new StyledToolTip() { Content = tooltip });
                            }
                        });
                    });
                }
                else
                {
                    if (this.AImage != null && this.AImage.Length > 0)
                    {
                        Image im = new Image() { Stretch = Stretch.None, Margin = new Thickness(0.0, 0.0, 4.0, 0.0) };
                        //VisualStateManager.GoToState(this,"Pressed",false);
                        BitmapImage bmp = new BitmapImage();
                        MemoryStream ms = new MemoryStream();
                        ms.Write(this.AImage, 0, this.AImage.Length);
                        bmp.SetSource(ms);
                        im.Source = bmp;
                        (this.Content as StackPanel).Children.Add(im);
                    }
                    else
                    {
                        if (this.ABitmapImage != null)
                        {
                            ((StackPanel)this.Content).Children.Add(new Image() { Source = this.ABitmapImage, Stretch = Stretch.None, Margin = new Thickness(0.0, 0.0, 4.0, 0.0) });
                        }
                    }
                    TextBlock tb = new TextBlock();
                        tb.Text = this.AText;
                        (base.Content as StackPanel).Children.Add(tb);                       
                    if (this.AShowToolTips && !string.IsNullOrEmpty(this.AToolTipText))
                    {
                        ToolTipService.SetToolTip(this, new StyledToolTip() { Content = this.AToolTipText });
                    }
                }
            }
            if (this.AFont != null)
            {
                base.FontFamily = new FontFamily(this.AFont.FamilyName);
                base.FontSize = this.AFont.Size;
                if (this.AFont.Italic)
                {
                    base.FontStyle = FontStyles.Italic;
                }
                if (this.AFont.Bold)
                {
                    base.FontWeight = FontWeights.Bold;
                }
            }
            Color emptyColor = Color.FromArgb(0, 0, 0, 0);
            if (this.AForeColor != emptyColor)
            {
                base.Foreground = new SolidColorBrush(this.AForeColor);
            }
            if (this.ABackColor != emptyColor)
            {
                if (this.ABackColor2 != emptyColor)
                {
                    GradientStopCollection coll = new GradientStopCollection();
                    coll.Add(new GradientStop() { Color = this.ABackColor });
                    coll.Add(new GradientStop() { Color = this.ABackColor2 });
                    base.Background = new LinearGradientBrush(coll, 45.0);
                }
                else
                {
                    base.Background = new SolidColorBrush(this.ABackColor);
                }
            }
            //switch (this.AButtonStyle)
            //{
                //case BorderStyles.HotFlat:
                //case BorderStyles.Flat:
            //    case BorderStyles.NoBorder:
            //        base.BorderThickness = new Thickness(0.0);
            //        break;
            //    default:
            //        break;
            //}
           

        }


        #endregion
    }
}